﻿app.factory('MessageService', function ($http, $q) {
    var chatArray = [];

    var addMessage = function (name, message) {
        var m = {
            name: name,
            text: message,
            isActive: true
        };

        chatArray.push(m);
    };

    var removeMessage = function (msgObj) {
        msgObj.isActive = !msgObj.isActive;
    }

    var getMessages = function () {

        var deferred = $q.defer();

        $http({
            url: 'https://nicksmessages.firebaseio.com/messages/.json',
            method: 'GET'
        }).success(function (data) {
            chatArray.length = 0;
            for (var chatId in data) {
                chatArray.push(data[chatId]);
            }

            deferred.resolve(chatArray);
        }).error(function () {
            deferred.reject();
        });

        return deferred.promise;
    }

    return {
        addMessage: addMessage,
        removeMessage: removeMessage,
        getMessages: getMessages
    };
});